package handler

import (
	"2301house/api/request"
	"2301house/api/resp"
	"2301house/consts"
	"2301house/internal/dao"
	"2301house/internal/model"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"github.com/share309/gojwt"
	"time"
)

func Register(c *gin.Context) {
	var req request.User
	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 10000, "参数错误", err.Error())
		return
	}
	var user model.User
	dao.GetOneByFields(&model.User{
		Mobile: req.Mobile,
	}, &user)
	if user.Id != 0 {
		resp.Error(c, 10000, "当前用户已存在", nil)
		return
	}
	result := dao.Create(&model.User{
		Mobile:   req.Mobile,
		Password: req.Password,
		UType:    req.UType,
	})
	if !result {
		resp.Error(c, 10000, "注册失败", nil)
		return
	}
	resp.Success(c, "注册成功", nil)
}

func Login(c *gin.Context) {
	var req request.User
	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 10000, "参数错误", err.Error())
		return
	}
	var user model.User
	dao.GetOneByFields(&model.User{
		Mobile: req.Mobile,
	}, &user)
	if user.Id == 0 {
		resp.Error(c, 10000, "当前用户不存在", nil)
		return
	}
	token, err := gojwt.NewJWT(consts.JWT_KEY).CreateToken(gojwt.CustomClaims{
		ID: user.Id,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() + 86400*3, //3天有效期
		},
	})
	if err != nil {
		resp.Error(c, 10000, "生成token失败", err.Error())
	}
	resp.Success(c, "OK", token)
}

func PerToken(c *gin.Context) {
	token, err := gojwt.NewJWT(consts.JWT_KEY).CreateToken(gojwt.CustomClaims{
		ID: c.GetUint("userId"),
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() + 3600*24*3,
		},
	})
	if err != nil {
		resp.Error(c, 1000, "刷新失败", err.Error())
		return
	}
	resp.Success(c, "刷新成功", token)
}
